import store from '@/utils/store'
import router from '@/router'
import NSys from '@/n-sys.js';
import auth from '@/utils/auth.js'
const {base,conf:globalConf,t, msg, ElUi:{ MessageBox} ,navProg   } = NSys;

// store.set('tokenInfo', {token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InJvb3QiLCJleHAiOjE3NDAxMDUzNDB9.sVXp_z2L_WLP5ly2UpM2Z0MpSlBALpzBE7l1G7LRaw8'});
export default (conf ={}) => {
	base.params.merge(conf,{
		baseUrl: globalConf.env.baseUrl, timeout: 30000,
		formatRes:null, msg:true,   showNavProg:true,expandConf:false,
		headers:{ 
			"Authorization": store.tokenInfo && store.tokenInfo.token  || undefined,
			"content-type": 'application/json',
		}
	})
	
	conf.showNavProg && navProg.start('bottom')
	conf.content = base.request(conf).then(res=>{
		conf.showNavProg && navProg.end()
		conf.formatRes && conf.formatRes({conf, res,cache})
		
		if(base.isType(res) === 'object' && !base.isEmpty(res.code) ) res.code *= 1; 
		if(!res || res.code !== globalConf.reqCode ) {

			res && conf.msg && conf.responseType === 'json' && msg(res && res.msg || '请求错误',2);
			
			// 判断token是否过期
			if( res && res.code === 401) {
				auth.logout()
				router.push(`/login?redirect=${ router.currentRoute.fullPath}`)
			}
			
			!res && conf.msg && msg('请求错误',2);
		}
		
		return conf.responseType === 'json' ? (res || {}) : res;
	})
	.catch(err => {
		conf.showNavProg && navProg.end();
		console.log(err)
		if(conf.msg) msg(`${t('出现错误')}：${err}, ${t('请刷新重试')}`,2)
		return conf.responseType === 'json'  ? {code: 'ERR'} : false;
	});
	

	return conf.expandConf ? conf : conf.content;
	
}
